package com.chagee.store.operation.server.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.alibaba.fastjson.JSON;
import com.chagee.store.operation.api.enums.PushFinanceStatusEnum;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.enums.LarkMessageTypeEnum;
import com.chagee.store.operation.server.entity.StoreSettlementDO;
import com.chagee.store.operation.server.event.service.StoreSettlementBaseService;
import com.chagee.store.operation.server.model.info.LarkMessageInfo;
import com.chagee.store.operation.server.service.biz.StoreSettlementBizService;
import com.chagee.store.operation.server.service.third.FeiShuSendService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 结算单待支付通知
 * @Author : hk
 * @Date : 2025/2/28
 */

@Component
@Slf4j
public class SettlementWaitPayJobHandler {


	@Resource
	private StoreSettlementBizService storeSettlementBizService;

	@Resource
	private StoreSettlementBaseService storeSettlementBaseService;

	@Resource
	private FeiShuSendService feiShuSendService;


	/**
	 * 每日10点; 推送加盟性质 待支付 超时 结算单
	 * @param param
	 * @return
	 */
	@XxlJob("pushWaitPayOutTimeSettlement")
	public ReturnT<String> pushWaitPayOutTimeSettlementMsg(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = DateUtil.timer();
		log.info("加盟性质待支付状态结算单发送飞书定时任务开始,traceId :{}", span.getTraceId());
		try {
			if (StringUtils.isNotBlank(param)) {
				//结算单号
				List<String> settlementNos = Arrays.stream(param.split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
				List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.batchQuerySettlement(settlementNos);
				sendFeiShuMsg(storeSettlementDOS);
			}else {
				//72小时后时间
				LocalDateTime dateTime = LocalDateTime.now();
				LocalDateTime cutoffTime = dateTime.minusHours(CommonConstant.WAIT_PAY_OUT_TIME);

				long startIndex = 0L;
				while (true) {
					List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.queryWaitPaySettlement(startIndex, cutoffTime);
					if (CollectionUtils.isEmpty(storeSettlementDOS)) {
						break;
					}
					log.info("加盟性质待支付状态结算单 :{}", JSON.toJSONString(storeSettlementDOS));

					sendFeiShuMsg(storeSettlementDOS);

					startIndex = Math.toIntExact(storeSettlementDOS.stream().map(StoreSettlementDO::getId).max(Comparator.naturalOrder()).orElse(0L));
				}
			}

		} catch (Exception e) {
			XxlJobLogger.log("加盟性质待支付状态结算单发送飞书定时任务异常，异常信息:", e);
			log.error("加盟性质待支付状态结算单发送飞书定时任务异常 => param : {} => 异常信息 :", param, e);
		}
		XxlJobLogger.log("加盟性质待支付状态结算单发送飞书定时任务结束，共耗时:{},TraceId:{}", timer.intervalRestart(), span.getTraceId());
		return ReturnT.SUCCESS;
	}

	//飞书通知
	private void sendFeiShuMsg(List<StoreSettlementDO> storeSettlementDOS) {
		for (StoreSettlementDO entry : storeSettlementDOS) {
			try {
				LarkMessageInfo messageInfo = new LarkMessageInfo();
				messageInfo.setStoreNo(entry.getStoreNo());
				messageInfo.setType(LarkMessageTypeEnum.settlementWaitPay.getType());
				messageInfo.setSettlementNo(entry.getSettlementNo());
				feiShuSendService.sendFeiShuMsg(messageInfo);
				log.info("结算单{}待支付超时飞书通知成功", JSON.toJSONString(entry.getSettlementNo()));
			} catch (Exception e) {
				log.error("结算单{}待支付超时飞书通知失败", entry.getSettlementNo(), e);
			}
		}
	}

}
